package com.fable.common.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.util.DateUtils;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;

/**
 * @Author : guozhenhu
 * @date: 2023/8/28
 * @Description : 管理
 **/
@Slf4j
@Component
public class TaskUtils {


    @XxlJob(value = "MSG001fileHandler")
//    @Scheduled(cron = "0/2 * * * * ?")
    public void doTask() {
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMAT_19));
        String params = XxlJobHelper.getJobParam();
        log.info("------------------>执行时间：" + time + "，参数--->" + params);
    }

    @XxlJob(value = "ClearFileHandler")
    public void doTaskClear() {
        String logPath = System.getProperty("user.dir") + File.separator + "log" + File.separator;
        String time = DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN);
        String[] infoAndError = {"error", "info", "xxl-job"};
        for (String array : infoAndError) {
            File file = new File(logPath + array);
            if ("xxl-job".equals(array)) {
                try {
                    if (file.isDirectory()) {
                        File[] files = file.listFiles();
                        if (files != null) {
                            for (File f : files) {
                                if (!f.getName().equals(time)) {
                                    Files.walk(f.toPath())
                                            .sorted(Comparator.reverseOrder())
                                            .map(Path::toFile)
                                            .forEach(File::delete);
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    log.error("异常", e);
                }
            } else {
                if (file.exists()) {
                    File[] files = file.listFiles();
                    assert files != null;
                    for (File f : files) {
                        String[] strings = f.getName().split("\\.");
                        if (!strings[1].equals(time)) {
                            f.delete();
                        }
                    }
                }
            }
        }
        String params = XxlJobHelper.getJobParam();
        log.info("------------------>执行时间：" + time + "，参数--->" + params);
    }
}
